package birdsong.filter;

import java.util.ArrayList;

public class MonitorEqualsMessage extends Monitor {

    public MonitorEqualsMessage(double timeout, int nMaxDisconnect, int nMaxWarning) {
	super(timeout, nMaxDisconnect, nMaxWarning);
    }

    /*
     * Checks if the monitor receives in an interval <timeout> The number of
     * messages <nMaxWarning> represents the number of equal messages needed to
     * send a warning to the user Use it to check and insert the message in the
     * queue
     */

    /**
     * @return true if the monitor received <nMaxWarning> equal messages in less
     *         than <timeout>
     * @return false otherwise
     */
    @Override
    public boolean sendWarning() {
	ArrayList<Message> messagesList = getList();
	int sizeList = messagesList.size();
	int nOccurrences = 0;
	Message key = messagesList.get(sizeList - 1);
	Message test;
	if (sizeList >= getNMaxWarning()) {
	    for (int i = sizeList - 2; i >= 0; i--) {
		test = messagesList.get(i);
		if (((key.getMessage()).equals(test.getMessage())) && ((key.getDate() - test.getDate()) < getTimeout()))
		    nOccurrences++;
	    }
	}
	if (nOccurrences + 1 == getNMaxWarning())
	    return true;

	return false;
    }

    /*
     * Checks if the monitor receives in an interval <timeout> The number of
     * messages <nMaxWarning> represents the number of equal messages needed to
     * disconnect the user Use it to check and insert the message in the queue
     */

    /**
     * @return true if the monitor received <nMaxWarning> equal messages in less
     *         than <timeout>
     * @return false otherwise
     */

    @Override
    public boolean disconnectClient() {
	ArrayList<Message> messagesList = getList();
	int sizeList = messagesList.size();
	int nOccurrences = 0;
	Message key = messagesList.get(sizeList - 1);
	Message test;
	if (sizeList >= getNMaxDisconnect()) {
	    for (int i = sizeList - 2; i >= 0; i--) {
		test = messagesList.get(i);
		if (((key.getMessage()).equals(test.getMessage())) && ((key.getDate() - test.getDate()) < getTimeout()))
		    nOccurrences++;
	    }
	}
	if (nOccurrences + 1 == getNMaxDisconnect())
	    return true;

	return false;
    }

}
